<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { currentUser } from '../user';

const searchQuery = ref('');
const searchResults = ref([]);
const searchHistory = ref([]);
const showDropdown = ref(false);
const router = useRouter();

// 监听热搜词填充事件
const handleFillSearchInput = (event) => {
  searchQuery.value = event.detail.keyword;
};

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('fill-search-input', handleFillSearchInput);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('fill-search-input', handleFillSearchInput);
});

function onFocus() {
  showDropdown.value = true; // 显示下拉框
}

async function onInput() {
  if (!searchQuery.value) {
    searchResults.value = [];
    return;
  }
  showDropdown.value = true;
  // 同时搜索activity、nickname和topic
  const [activityRes, nicknameRes, topicRes] = await Promise.all([
    axios.get('/search', {
      params: {
        type: 'activity',
        keyword: searchQuery.value
      }
    }),
    axios.get('/search', {
      params: {
        type: 'nickname',
        keyword: searchQuery.value
      }
    }),
    axios.get('/search', {
      params: {
        type: 'topic',
        keyword: searchQuery.value
      }
    })
  ]);
  // 合并结果，分别标记type
  const activities = (activityRes.data.data || []).map(item => ({ ...item, type: 'activity' }));
  const nicknames = (nicknameRes.data.data || []).map(item => ({
    ...item,
    type: 'nickname', // 统一标记为昵称
    name: item.nickname || item.name || item.username
  }));
  const topics = (topicRes.data.data || []).map(item => ({
    ...item,
    type: 'topic', // 标记为话题
    name: item.content, // 使用话题内容作为名称
    displayName: `#${item.content}` // 添加#前缀用于显示
  }));
  searchResults.value = [...activities, ...nicknames, ...topics];
}

function selectResult(item) {
  searchQuery.value = item.name;
  // 只有当用户已登录且不是游客时才保存搜索历史
  if (currentUser.id && currentUser.id !== 'guest') {
    try {
      // 将userId转换为数字类型 - 后端需要Long类型
      const userId = parseInt(currentUser.id);
      
      // 存历史到后端（表单格式），添加用户ID
      axios.post('/search/history', new URLSearchParams({ 
        keyword: item.name,
        userId: userId.toString()
      }));
    } catch (error) {
      console.error('保存搜索历史失败:', error);
      // 即使保存失败也继续搜索流程
    }
  }
  
  // 跳转到搜索结果页，传递搜索内容
  if (item.type === 'topic') {
    // 话题类型，跳转到搜索结果页并自动选择话题标签
    router.push({
      name: 'SearchResult',
      query: { q: item.name, type: 'topic', topicId: item.id }
    });
  } else {
    // 其他类型，正常跳转
    router.push({
      name: 'SearchResult',
      query: { q: item.name }
    });
  }
  showDropdown.value = false;
}

function selectHistory(item) {
  searchQuery.value = item;
  doSearch();
  showDropdown.value = false;
}

function onBlur() {
  setTimeout(() => { showDropdown.value = false; }, 200);
}

// 执行搜索
const doSearch = async () => {
  if (!searchQuery.value.trim()) return;
  
  // 只有当用户已登录且不是游客时才保存搜索历史
  if (currentUser.id && currentUser.id !== 'guest') {
    try {
      // 将userId转换为数字类型 - 后端需要Long类型
      const userId = parseInt(currentUser.id);
      console.log('保存搜索历史，用户ID:', userId, '关键词:', searchQuery.value);
      
      // 保存搜索历史到后端 - 使用URLSearchParams格式
      await axios.post('/search/history', new URLSearchParams({
        userId: userId.toString(),
        keyword: searchQuery.value
      }));
      
      // 更新本地搜索历史
      if (!searchHistory.value.includes(searchQuery.value)) {
        searchHistory.value.unshift(searchQuery.value);
        if (searchHistory.value.length > 10) searchHistory.value = searchHistory.value.slice(0, 10);
      }
    } catch (error) {
      console.error('保存搜索历史失败:', error);
      // 即使保存失败也继续搜索流程
    }
  }
  
  // 跳转到搜索结果页
  router.push({
    name: 'SearchResult',
    query: { q: searchQuery.value }
  });
}

function handleDeleteHistory(idx) {
  // 从数组中移除项目
  const removedKeyword = searchHistory.value.splice(idx, 1)[0];
  
  // 如果用户已登录，也从后端删除
  if (currentUser.id && currentUser.id !== 'guest') {
    try {
      const userId = parseInt(currentUser.id);
      // 调用后端删除API
      axios.delete('/search/history', {
        params: {
          keyword: removedKeyword,
          userId: userId.toString()
        }
      }).then(() => {
        console.log('从后端删除搜索历史成功:', removedKeyword);
      }).catch(error => {
        console.error('删除搜索历史失败:', error);
      });
    } catch (error) {
      console.error('删除搜索历史失败:', error);
    }
  }
}

// 加载历史记录（从后端）- 仅当用户已登录且不是游客时
onMounted(async () => {
  // 只有当用户已登录且不是游客时才加载搜索历史
  if (currentUser.id && currentUser.id !== 'guest') {
    try {
      // 将userId转换为数字类型 - 后端需要Long类型
      const userId = parseInt(currentUser.id);
      console.log('正在获取搜索历史，用户ID:', userId);
      const res = await axios.get('/search/history', { 
        params: { userId: userId.toString() } 
      });
      console.log('搜索历史响应:', res.data);
      if (res.data && res.data.code === 200) {
        // 过滤掉undefined或null值，确保每个历史记录都有值
        searchHistory.value = (res.data.data || [])
          .map(item => item.keyword)
          .filter(keyword => keyword !== undefined && keyword !== null);
        console.log('处理后的搜索历史:', searchHistory.value);
      }
    } catch (error) {
      console.error('获取搜索历史失败:', error);
    }
  }

  // 登录后自动拉取用户信息
  if (currentUser.id) {
    try {
      const userRes = await axios.get(`/search/user/${currentUser.id}`);
      if (userRes.data && userRes.data.data) {
        currentUser.nickname = userRes.data.data.nickname;
        currentUser.avatar = userRes.data.data.avatar;
      }
    } catch (e) {
      // 拉取失败时不处理，保持默认
    }
  }
});
</script>

<template>
  <div class="search-bar-wrapper">
    <div class="search-input-wrapper">
      <input
        v-model="searchQuery"
        @focus="onFocus"
        @input="onInput"
        @keydown.enter="doSearch"
        @blur="onBlur"
        placeholder="UP主开箱错误激活码"
      />
      <img
        width="24"
        height="24"
        src="https://img.icons8.com/material-rounded/96/search-more.png"
        alt="搜索"
        class="search-icon"
        @click="doSearch"
      />
    </div>
    <!-- 搜索下拉菜单 -->
    <div v-show="showDropdown" class="search-dropdown">
      <!-- 只显示activity和nickname类型 -->
      <div v-if="searchQuery">
        <div
          v-for="item in searchResults"
          :key="item.type + '-' + item.id"
          class="dropdown-item bar-item"
          @mousedown.prevent="selectResult(item)"
        >
          <img
            v-if="item.type === 'activity'"
            src="https://img.icons8.com/material-rounded/96/search-more.png"
            width="24"
            height="24"
            alt="activity"
            class="result-icon"
          />
          <img
            v-else-if="item.type === 'nickname'"
            src="https://img.icons8.com/material/96/guest-male--v1.png"
            width="24"
            height="24"
            alt="nickname"
            class="result-icon"
          />
          <img
            v-else-if="item.type === 'topic'"
            src="https://img.icons8.com/material-rounded/96/hashtag.png"
            width="24"
            height="24"
            alt="topic"
            class="result-icon"
          />
          <span class="result-name">{{ item.type === 'topic' ? item.displayName : item.name }}</span>
          <span v-if="item.type === 'activity'" class="result-type-label">动态</span>
          <span v-else-if="item.type === 'nickname'" class="result-type-label">用户</span>
          <span v-else-if="item.type === 'topic'" class="result-type-label">话题</span>
        </div>
        <div v-if="searchResults.length === 0" class="dropdown-empty">未找到相关内容</div>
      </div>
      <!-- 如果没有搜索关键词，则显示搜索历史 -->
      <div v-else>
        <div class="dropdown-title">搜索历史</div>
        <div
          v-for="(item, idx) in searchHistory"
          :key="idx"
          class="dropdown-item"
          @mousedown.prevent="selectHistory(item)"
        >
          <img class="icon" src="https://img.icons8.com/material/96/clock--v1.png" width="24" height="24" alt="历史" />
          <span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{ item || '未知搜索' }}</span>
          <span class="delete-x" @mousedown.stop.prevent="handleDeleteHistory(idx)">×</span>
        </div>
        <div v-if="searchHistory.length === 0" class="dropdown-empty">暂无历史记录</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-bar-wrapper {
  position: relative;
  width: 100%;
  max-width: 450px;
  margin: 0 auto;
}
.search-input-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  width: 100%;
  max-width: 450px;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 5px 15px;
  background-color: #f5f5f5;
  margin: 0 auto;
}
.search-input-wrapper input {
  border: none;
  outline: none;
  flex-grow: 1;
  padding: 5px;
  background-color: transparent;
  font-size: 14px;
  text-align: center;
}
.search-icon {
  margin-left: 30px;
}
.search-dropdown {
  position: absolute;
  top: 44px;
  left: 0;
  right: 0;
  background: white !important;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  z-index: 99999 !important;
  max-height: 320px;
  overflow-y: auto;
  min-width: 100%;
  padding: 6px 0;
  animation: fadeIn 0.18s;
}
.dropdown-title {
  font-size: 13px;
  color: #888;
  padding: 8px 20px 4px 20px;
  font-weight: 500;
}
.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px;
  color: #222;
  transition: background 0.18s, color 0.18s;
  border-radius: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.bar-item {
  background: #fff;
  border-bottom: 1px solid #f2f2f2;
  min-height: 48px;
  padding: 0 24px;
  display: flex;
  align-items: center;
  gap: 16px;
}
.bar-item:last-child {
  border-bottom: none;
}
.result-icon {
  width: 24px;
  height: 24px;
  margin-right: 12px;
  flex-shrink: 0;
  opacity: 0.7;
}
.result-name {
  flex: 1;
  font-size: 16px;
  color: #222;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dropdown-item:hover {
  background: #f0f6ff;
  color: #1976d2;
}
.dropdown-empty {
  text-align: center;
  color: #888;
  padding: 10px 0;
}
.result-type-label {
  font-size: 12px;
  color: #aaa;
  margin-left: 8px;
}
.delete-x {
  color: #bbb;
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  transition: color 0.18s;
  user-select: none;
}
.delete-x:hover {
  color: #f56c6c;
}
</style>
